#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <utmp.h>

int utmp_open(char *);
struct utmp * utmp_next();
int utmp_reload();
void utmp_close();

#define NRECS 16						//a buffer stores 16 utmp records
#define NULLUT ((struct utmp *)NULL)
#define UTSIZE (sizeof(struct utmp))	//size of one utmp record

static char utmpbuf[NRECS * UTSIZE];	//buffer that stores utmp records
static int num_recs;					//numbers of stored records in a buffer
static int cur_rec;						//numbers of readed records
static int fd_utmp = -1;

int utmp_open(char * filename){
	fd_utmp = open(filename, O_RDONLY);
	cur_rec = num_recs = 0;
	return fd_utmp;
}

struct utmp * utmp_next(){
	struct utmp * recp;
	if (fd_utmp == -1){
		return NULLUT;
	}
	if (cur_rec == num_recs && utmp_reload() == 0){
		return NULLUT;
	}
	recp = (struct utmp *) &utmpbuf[cur_rec * UTSIZE];	//address of next record
	cur_rec++;
	return recp;
}

int utmp_reload(){
	int amt_read;
	amt_read = read(fd_utmp, utmpbuf, NRECS * UTSIZE);
	num_recs = amt_read / UTSIZE;
	cur_rec = 0;
	return num_recs;
}

void utmp_close(){
	if (fd_utmp != -1){
		close(fd_utmp);
	}
}
